<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from "vue";
import { Popup, showToast } from "vant";
import { useRouter } from "vue-router";
import { getCurrentUser, getUserDisplayName, getUserAvatar, getUserId, logout as userLogout } from '@/utils/userStore';
import { loadUserCoupons, getAllCoupons, getAvailableCoupons, getCouponStats, type Coupon } from '@/utils/couponStore';
import { loadUserFavorites, getAllFavorites, removeFromFavorites, getFavoriteStats, getFavoritesByType, type FavoriteVideo } from '@/utils/favoriteStore';
import { loadUserPoints, getUserPoints, getPointsProducts, exchangePointsProduct, getPointsStats, getPointsRecords, getMemberPoints } from '@/utils/pointsStore';
import { getMembershipCard, getCurrentMemberLevel, getNextMemberLevel, getUpgradeProgress } from '@/utils/membershipStore';
import { messages } from '@/utils/i18n';

const router = useRouter();


// 国际化语言包
const createI18nConfig = () => ({
  zh: {
    eyeControlCenter: "眼神控制中心",
    viaEyeMovement: "通过眼神移动实现键盘输入",
    systemStatus: "系统状态",
    cameraStatus: "摄像头状态",
    eyeTracking: "眼神追踪",
    inputMode: "输入模式",
    typingMode: "打字模式",
    eyeMode: "眼神模式",
    sensitivitySettings: "灵敏度设置",
    movementSensitivity: "移动灵敏度",
    blinkThreshold: "眨眼检测阈值",
    stopTracking: "停止追踪",
    startTracking: "开始追踪",
    myNotes: "我的笔记",
    myFavorites: "我的收藏",
    myFollows: "我的关注",
    myCoupons: "我的优惠券",
    mall: "商城",
    settings: "设置",
    personalInfo: "个人基础信息",
    privacySecurity: "隐私与安全",
    privacySettings: "隐私设置",
    notifications: "消息与提醒",
    terms: "协议与条款",
    about: "关于爱运动",
    language: "国际化语言",
    customerService: "客服中心",
    realNameAuth: "实名认证",
    logout: "退出登录",
    sportRecord: "运动记录",
    cumulativeTime: "累计时间",
    thisWeekData: "本周运动数据",
    today: "今日",
    weekOverview: "本周运动数据",
    followList: "我的关注",
    total: "共",
    noFollowedUsers: "暂无关注的用户",
    discoverPeople: "去社区发现更多有趣的人吧~",
    cancelFollow: "取消关注",
    followTime: "关注时间：",
    myFavoritesList: "我的收藏",
    noFavorites: "暂无收藏视频",
    collectVideos: "去视频页面收藏喜欢的内容吧~",
    removeFavorite: "移除",
    favoriteTime: "收藏时间：",
    myCouponsList: "我的优惠券",
    noAvailableCoupons: "暂无可用优惠券",
    noUsedCoupons: "暂无已使用优惠券",
    noExpiredCoupons: "暂无过期优惠券",
    getMoreCoupons: "去商城购物获取更多优惠券吧~",
    available: "可用",
    used: "已用",
    expired: "过期",
    minSpend: "满",
    yuan: "元可用",
    expires: "到期",
    from: "来源：",
    sportData: "运动数据",
    goToVideoDetail: "查看视频详情",
    confirmLogout: "确定要退出登录吗？",
    sendContent: "发送内容：",
    changeCover: "更换封面",
    uploading: "上传中...",
    days: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
  },
  en: {
    eyeControlCenter: "Eye Control Center",
    viaEyeMovement: "Keyboard input via eye movement",
    systemStatus: "System Status",
    cameraStatus: "Camera Status",
    eyeTracking: "Eye Tracking",
    inputMode: "Input Mode",
    typingMode: "Typing Mode",
    eyeMode: "Eye Mode",
    sensitivitySettings: "Sensitivity Settings",
    movementSensitivity: "Movement Sensitivity",
    blinkThreshold: "Blink Threshold",
    stopTracking: "Stop Tracking",
    startTracking: "Start Tracking",
    myNotes: "My Notes",
    myFavorites: "My Favorites",
    myFollows: "My Follows",
    myCoupons: "My Coupons",
    mall: "Mall",
    settings: "Settings",
    personalInfo: "Personal Information",
    privacySecurity: "Privacy & Security",
    privacySettings: "Privacy Settings",
    notifications: "Messages & Notifications",
    terms: "Terms & Agreements",
    about: "About Sports App",
    language: "Language",
    customerService: "Customer Service",
    realNameAuth: "Real-name Authentication",
    logout: "Logout",
    sportRecord: "Sports Record",
    cumulativeTime: "Cumulative Time",
    thisWeekData: "This Week's Data",
    today: "Today",
    weekOverview: "Weekly Sports Data",
    followList: "My Follows",
    total: "Total",
    noFollowedUsers: "No followed users",
    discoverPeople: "Discover more interesting people in the community~",
    cancelFollow: "Unfollow",
    followTime: "Followed on: ",
    myFavoritesList: "My Favorites",
    noFavorites: "No favorite videos",
    collectVideos: "Go to video page to collect favorite content~",
    removeFavorite: "Remove",
    favoriteTime: "Collected on: ",
    myCouponsList: "My Coupons",
    noAvailableCoupons: "No available coupons",
    noUsedCoupons: "No used coupons",
    noExpiredCoupons: "No expired coupons",
    getMoreCoupons: "Get more coupons by shopping in the mall~",
    available: "Available",
    used: "Used",
    expired: "Expired",
    minSpend: "Min. spend ",
    yuan: " yuan",
    expires: "expires on",
    from: "From: ",
    sportData: "Sports Data",
    goToVideoDetail: "View Video Details",
    confirmLogout: "Are you sure to logout?",
    sendContent: "Send content: ",
    changeCover: "Change Cover",
    uploading: "Uploading...",
    days: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
  },
  jp: {
    eyeControlCenter: "アイコントロールセンター",
    viaEyeMovement: "目の動きでキーボード入力を実現",
    systemStatus: "システム状態",
    cameraStatus: "カメラ状態",
    eyeTracking: "アイトラッキング",
    inputMode: "入力モード",
    typingMode: "タイピングモード",
    eyeMode: "アイモード",
    sensitivitySettings: "感度設定",
    movementSensitivity: "移動感度",
    blinkThreshold: "瞬き検出しきい値",
    stopTracking: "追跡を停止",
    startTracking: "追跡を開始",
    myNotes: "マイノート",
    myFavorites: "お気に入り",
    myFollows: "フォロー中",
    myCoupons: "クーポン",
    mall: "ショッピングモール",
    settings: "設定",
    personalInfo: "個人基本情報",
    privacySecurity: "プライバシーとセキュリティ",
    privacySettings: "プライバシー設定",
    notifications: "メッセージと通知",
    terms: "利用規約",
    about: "スポーツアプリについて",
    language: "言語設定",
    customerService: "カスタマーサービス",
    realNameAuth: "実名認証",
    logout: "ログアウト",
    sportRecord: "運動記録",
    cumulativeTime: "累計時間",
    thisWeekData: "今週のデータ",
    today: "今日",
    weekOverview: "週間運動データ",
    followList: "フォロー一覧",
    total: "合計",
    noFollowedUsers: "フォローしているユーザーはいません",
    discoverPeople: "コミュニティでもっと多くの人を発見しよう~",
    cancelFollow: "フォロー解除",
    followTime: "フォロー日時: ",
    myFavoritesList: "お気に入り一覧",
    noFavorites: "お気に入りの動画はありません",
    collectVideos: "動画ページでお気に入りのコンテンツを収集しましょう~",
    removeFavorite: "削除",
    favoriteTime: "収集日時: ",
    myCouponsList: "クーポン一覧",
    noAvailableCoupons: "利用可能なクーポンはありません",
    noUsedCoupons: "使用済みのクーポンはありません",
    noExpiredCoupons: "期限切れのクーポンはありません",
    getMoreCoupons: "モールで買い物をして、さらに多くのクーポンを獲得しましょう~",
    available: "利用可能",
    used: "使用済み",
    expired: "期限切れ",
    minSpend: "最低購入額 ",
    yuan: "元以上",
    expires: "有効期限",
    from: "発行元: ",
    sportData: "運動データ",
    goToVideoDetail: "動画詳細を表示",
    confirmLogout: "ログアウトしてもよろしいですか？",
    sendContent: "送信内容: ",
    changeCover: "カバーを変更",
    uploading: "アップロード中...",
    days: ["月", "火", "水", "木", "金", "土", "日"]
  }
});

const i18n = createI18nConfig();

// 语言状态管理
const currentLang = ref(localStorage.getItem('appLang') || 'zh');
const showLangSelector = ref(false);
const supportedLangs = [
  { code: 'zh', name: '中文' },
  { code: 'en', name: 'English' },
  { code: 'jp', name: '日本語' }
];

// 监听语言变化，实时保存到本地存储
watch(currentLang, (newLang) => {
  localStorage.setItem('appLang', newLang);
  // 更新图表日期为当前语言
  updateChartDays();
});

// 更新图表日期为当前语言
const updateChartDays = () => {
  chartData.value = [
    { day: messages[(currentLang.value as string) as keyof typeof messages].days[0], value: 45, label: '45min' },
    { day: messages[(currentLang.value as string) as keyof typeof messages].days[1], value: 52, label: '52min' },
    { day: messages[(currentLang.value as string) as keyof typeof messages].days[2], value: 38, label: '38min' },
    { day: messages[(currentLang.value as string) as keyof typeof messages].days[3], value: 65, label: '65min' },
    { day: messages[(currentLang.value as string) as keyof typeof messages].days[4], value: 48, label: '48min' },
    { day: messages[(currentLang.value as string) as keyof typeof messages].days[5], value: 72, label: '72min' },
    { day: messages[(currentLang.value as string) as keyof typeof messages].days[6], value: 58, label: '58min' }
  ];
};

// 切换语言
const changeLanguage = (lang: string) => {
  currentLang.value = lang;
  showLangSelector.value = false;
};

// 关注用户类型定义
interface FollowedUser {
  name: string;
  avatar: string;
  level: number;
  followedAt: string; // 关注时间
}

// 关注列表相关状态
const followedUsers = ref<FollowedUser[]>([]);
const showFollowList = ref(false);

// 优惠券相关状态
const showCouponList = ref(false);
const coupons = ref<Coupon[]>([]);
const couponStats = ref({ available: 0, used: 0, expired: 0, total: 0 });
const activeCouponTab = ref('available');

// 收藏相关状态
const showFavoriteList = ref(false)
const favorites = ref<FavoriteVideo[]>([])
const favoriteStats = ref({ total: 0, byType: { 跑步: 0, 骑行: 0, 瑜伽: 0, 健身: 0 } })
const activeFavoriteTab = ref('all')

// 积分和会员卡相关状态
const showMembershipCard = ref(false)
const showPointsMall = ref(false)
const showPointsRecords = ref(false)
const userPoints = ref(0)
const membershipCard = ref<ReturnType<typeof getMembershipCard> | null>(null)
const pointsProducts = ref<ReturnType<typeof getPointsProducts>>([])

// 添加记录类型定义
interface PointRecord {
  id: string;
  type: 'earn' | 'spend';
  amount: number;
  description: string;
  source: string;
  createTime: string;
}

// 修改记录数组类型
const pointsRecords = ref<PointRecord[]>([])
const pointsStats = ref({ current: 0, totalEarned: 0, totalSpent: 0, recordsCount: 0 })

// 使用真实用户数据
const userData = ref({
  id: "",
  name: "王紫冰",
  level: "Lv:2",
  sportData: {
    points: 4653,
    unit: "分钟",
    description: messages[(currentLang.value as string) as keyof typeof messages].cumulativeTime,
  },
});

// 初始化用户数据
const initUserData = () => {
  const user = getCurrentUser();
  if (user) {
    userData.value.id = getUserId();
    userData.value.name = getUserDisplayName();
  }
};

// 统一数据加载管理器
const dataManager = {
  loadFollows: () => {
    try {
      const data = JSON.parse(localStorage.getItem('followedUsers') || '{}')
      followedUsers.value = Object.entries(data).map(([name, data]: [string, any]) => ({
        name,
        avatar: data.avatar || 'https://randomuser.me/api/portraits/men/1.jpg',
        level: data.level || 1,
        followedAt: data.followedAt || new Date().toISOString().slice(0, 10)
      }))
    } catch (error) {
      console.error('加载关注列表失败:', error)
    }
  },

  loadCoupons: () => {
    try {
      loadUserCoupons()
      coupons.value = getAllCoupons()
      couponStats.value = getCouponStats()
    } catch (error) {
      console.error('加载优惠券失败:', error)
    }
  },

  loadFavorites: () => {
    try {
      loadUserFavorites()
      favorites.value = getAllFavorites()
      favoriteStats.value = getFavoriteStats()
    } catch (error) {
      console.error('加载收藏失败:', error)
    }
  }
};

// 加载关注用户列表
const loadFollowedUsers = () => {
  dataManager.loadFollows();
};

// 加载优惠券列表
const loadCoupons = () => {
  dataManager.loadCoupons();
};

// 加载收藏列表
const loadFavorites = async () => {
  try {
    // 先从本地加载
    dataManager.loadFavorites();
    
    // 然后从后端同步
    const { syncFavoritesFromBackend } = await import('@/utils/favoriteStore');
    const syncCount = await syncFavoritesFromBackend();
    
    if (syncCount > 0) {
      // 如果有新增收藏，重新加载本地数据
      dataManager.loadFavorites();
      // 可以添加提示
      // showToast(`已同步${syncCount}个收藏视频`);
    }
  } catch (error) {
    console.error('加载收藏失败:', error);
  }
};

// 取消关注
const unfollowUser = (userName: string) => {
  try {
    // 从本地存储中移除
    const storedDataStr = localStorage.getItem('followedUsers') || '{}';
    const storedData = JSON.parse(storedDataStr);
    delete storedData[userName];
    localStorage.setItem('followedUsers', JSON.stringify(storedData));

    // 从列表中移除
    followedUsers.value = followedUsers.value.filter(user => user.name !== userName);

    console.log('已取消关注:', userName);
  } catch (error) {
    console.error('取消关注失败:', error);
  }
};

// 简化显示函数
const showModal = (type: 'follows' | 'coupons' | 'favorites') => {
  const actions = {
    follows: () => { dataManager.loadFollows(); showFollowList.value = true },
    coupons: () => { dataManager.loadCoupons(); showCouponList.value = true },
    favorites: () => { dataManager.loadFavorites(); showFavoriteList.value = true }
  }
  actions[type]()
}

// 更新函数调用
const showMyFollows = () => showModal('follows')
const showMyCoupons = () => showModal('coupons')
const showMyFavorites = () => showModal('favorites')

// 加载积分和会员数据
const loadPointsAndMembership = () => {
  loadUserPoints()

  // 根据运动时长计算积分（每10分钟1积分）
  const exerciseMinutes = userData.value.sportData.points // 4653分钟
  const calculatedPoints = Math.floor(exerciseMinutes / 10) // 应该是465积分

  console.log('运动时长:', exerciseMinutes, '计算积分:', calculatedPoints)

  // 如果会员积分为0，则根据运动时长设置会员积分
  if (getMemberPoints() === 0 && calculatedPoints > 0) {
    // 直接设置会员积分和可用积分
    const userId = getUserId()
    const memberPointsKey = `memberPoints_${userId}`
    const pointsKey = `userPoints_${userId}`

    localStorage.setItem(memberPointsKey, calculatedPoints.toString())
    localStorage.setItem(pointsKey, calculatedPoints.toString())

    // 重新加载积分数据
    loadUserPoints()
  }

  // 更新响应式变量
  userPoints.value = getUserPoints()

  // 重新获取会员卡信息以确保积分同步
  membershipCard.value = getMembershipCard()
  pointsProducts.value = getPointsProducts()
  pointsRecords.value = getPointsRecords()
  pointsStats.value = getPointsStats()

  console.log('积分加载完成:', {
    可用积分: userPoints.value,
    会员积分: getMemberPoints(),
    会员卡积分: membershipCard.value.points
  })
}

// 兑换积分商品
const exchangeProduct = async (productId: string) => {
  const product = pointsProducts.value.find(p => p.id === productId)
  if (!product) {
    showToast('商品不存在')
    return
  }

  if (userPoints.value < product.pointsCost) {
    showToast('积分不足，无法兑换')
    return
  }

  const success = exchangePointsProduct(productId)
  if (success) {
    showToast(`兑换成功！${product.name}已添加到您的账户`)
    loadPointsAndMembership() // 刷新数据
    loadCoupons() // 刷新优惠券数据
  } else {
    showToast('兑换失败，请稍后重试')
  }
}

// 根据类型过滤收藏
const filteredFavorites = computed(() => {
  if (activeFavoriteTab.value === 'all') {
    return favorites.value
  } else {
    return getFavoritesByType(activeFavoriteTab.value)
  }
})

// 移除收藏
const removeFavorite = (videoId: number) => {
  const success = removeFromFavorites(videoId)
  if (success) {
    loadFavorites() // 重新加载数据
    console.log('已移除收藏')
  }
}

// 跳转到视频详情
const goToVideoDetail = (video: FavoriteVideo) => {
  router.push({
    name: 'LLQxq',
    params: { id: video.id }
  })
}

// 根据状态过滤优惠券
const filteredCoupons = computed(() => {
  if (activeCouponTab.value === 'available') {
    const availableCoupons = coupons.value.filter(c => {
      const isAvailable = c.status === 'available';
      const notExpired = new Date(c.expireDate) > new Date();
      return isAvailable && notExpired;
    });
    return availableCoupons;
  } else if (activeCouponTab.value === 'used') {
    return coupons.value.filter(c => c.status === 'used');
  } else {
    return coupons.value.filter(c => c.status === 'expired' || new Date(c.expireDate) <= new Date());
  }
});

// 格式化日期
const formatDate = (dateStr: string) => {
  return dateStr.replace(/-/g, '.');
};

// 获取优惠券状态文本
const getCouponStatusText = (coupon: Coupon) => {
  if (coupon.status === 'used') return messages[currentLang.value as keyof typeof messages].used;
  if (new Date(coupon.expireDate) <= new Date()) return messages[(currentLang.value as string) as keyof typeof messages].expired;
  return messages[(currentLang.value as string) as keyof typeof messages].available;
};

// 跳转到用户详情
const goToUserDetail = (user: FollowedUser) => {
  router.push({
    name: 'Detail',
    query: {
      name: user.name,
      avatar: user.avatar,
      level: user.level,
      followed: 'true'
    }
  });
};

// 添加背景图相关的响应式变量
const backgroundImage = ref('https://ts4.tc.mm.bing.net/th/id/OIP-C.zEQYQuEU3D-KQjycY0Bk2QHaEs?rs=1&pid=ImgDetMain&o=7&rm=3');
const isChangingCover = ref(false);

// 计算真实的每周运动时间数据
const calculateWeeklyExerciseData = async () => {
  try {
    let records = [];

    // 优先从IndexedDB获取数据
    try {
      const { getAllFromStore, RECORDS_STORE } = await import('@/utils/indexedDB');
      const indexedDBRecords = await getAllFromStore(RECORDS_STORE);
      if (indexedDBRecords && indexedDBRecords.length > 0) {
        records = indexedDBRecords;
        console.log('从IndexedDB获取运动记录:', records.length, '条');
      } else {
        // 如果IndexedDB中没有数据，从localStorage获取
        const storedRecords = localStorage.getItem('runningHistory');
        records = storedRecords ? JSON.parse(storedRecords) : [];
        console.log('从localStorage获取运动记录:', records.length, '条');
      }
    } catch (error) {
      console.error('从IndexedDB获取数据失败，尝试localStorage:', error);
      // 出错时从localStorage获取
      const storedRecords = localStorage.getItem('runningHistory');
      records = storedRecords ? JSON.parse(storedRecords) : [];
    }

    console.log('解析后的记录数量:', records.length);

    // 获取当前周的开始日期（周一）和结束日期（周日）
    const now = new Date();
    const currentDay = now.getDay(); // 0=周日, 1=周一, ..., 6=周六
    const mondayOffset = currentDay === 0 ? -6 : 1 - currentDay; // 计算到周一的偏移
    const monday = new Date(now);
    monday.setDate(now.getDate() + mondayOffset);
    monday.setHours(0, 0, 0, 0);

    // 计算本周结束日期（周日 23:59:59）
    const sunday = new Date(monday);
    sunday.setDate(monday.getDate() + 6);
    sunday.setHours(23, 59, 59, 999);

    console.log('本周开始日期（周一）:', monday);
    console.log('本周结束日期（周日）:', sunday);

    // 初始化一周7天的数据（秒数）
    const weekDataSeconds = [0, 0, 0, 0, 0, 0, 0]; // 周一到周日，先用秒数累加

    // 遍历运动记录，计算本周每天的运动时间
    records.forEach((record: any) => {
      const recordDate = new Date(record.date);
      console.log('处理记录:', record.date, '时长:', record.duration);

      // 检查记录是否在本周内（周一到周日）
      if (recordDate >= monday && recordDate <= sunday) {
        const dayOfWeek = recordDate.getDay();
        const dayIndex = dayOfWeek === 0 ? 6 : dayOfWeek - 1; // 转换为0-6（周一到周日）

        // 先累加秒数
        weekDataSeconds[dayIndex] += record.duration;
        console.log(`记录日期: ${record.date}, 星期${dayOfWeek}, 索引${dayIndex}, 累加${record.duration}秒`);
      } else {
        console.log(`记录 ${record.date} 不在本周范围内，跳过`);
      }
    });

    // 将每天的总秒数转换为分钟（保留一位小数）
    const weekData = weekDataSeconds.map(seconds => {
      return Math.round((seconds / 60) * 10) / 10; // 转换为分钟并保留一位小数
    });

    console.log('每天总秒数:', weekDataSeconds);
    console.log('最终周数据（分钟）:', weekData);
    return weekData;
  } catch (error) {
    console.error('计算每周运动数据失败:', error);
    // 返回默认数据
    return [0, 0, 0, 0, 0, 0, 0];
  }
};

// 添加图表数据
const chartData = ref([
  { day: i18n[currentLang.value as keyof typeof i18n].days[0], value: 0, label: '0min' },
  { day: i18n[currentLang.value as keyof typeof i18n].days[1], value: 0, label: '0min' },
  { day: i18n[currentLang.value as keyof typeof i18n].days[2], value: 0, label: '0min' },
  { day: i18n[currentLang.value as keyof typeof i18n].days[3], value: 0, label: '0min' },
  { day: i18n[currentLang.value as keyof typeof i18n].days[4], value: 0, label: '0min' },
  { day: i18n[currentLang.value as keyof typeof i18n].days[5], value: 0, label: '0min' },
  { day: i18n[currentLang.value as keyof typeof i18n].days[6], value: 0, label: '0min' }
]);

// 更新图表数据的函数
const updateChartData = async () => {
  console.log('开始更新图表数据...'); // 添加调试日志
  const weeklyData = await calculateWeeklyExerciseData();

  // 更新当前日期索引
  currentDayIndex.value = getCurrentDayIndex();
  console.log('当前日期索引:', currentDayIndex.value); // 添加调试日志

  chartData.value = weeklyData.map((minutes, index) => ({
    day: i18n[currentLang.value as keyof typeof i18n].days[index],
    value: minutes,
    label: `${minutes}min`
  }));

  console.log('更新后的图表数据:', chartData.value); // 添加调试日志
};



// 监听页面可见性变化的函数
const handleVisibilityChange = () => {
  if (!document.hidden) {
    console.log('页面重新可见，刷新数据...');
    updateChartData();
    loadPointsAndMembership(); // 添加这行来刷新积分和会员卡数据
    dataManager.loadCoupons(); // 刷新优惠券数据（如果支付时使用了优惠券）
  }
};

// 计算图表路径
const chartPath = computed(() => {
  const width = 120;
  const height = 50;
  const padding = 10;
  const maxValue = Math.max(...chartData.value.map(d => d.value));

  // 防止除零运算，当所有数据为0时使用默认值
  const safeMaxValue = maxValue > 0 ? maxValue : 1;

  const points = chartData.value.map((item, index) => {
    const x = padding + (index * (width - 2 * padding)) / (chartData.value.length - 1);
    const y = height - padding - ((item.value / safeMaxValue) * (height - 2 * padding));
    return `${x},${y}`;
  });

  return points.join(' ');
});

// 计算渐变路径（用于填充区域）
const gradientPath = computed(() => {
  const width = 120;
  const height = 50;
  const padding = 10;

  const pathPoints = chartPath.value;
  if (!pathPoints || pathPoints.trim() === '') {
    // 如果没有有效路径，返回底部直线
    return `M ${padding},${height - padding} L ${width - padding},${height - padding} Z`;
  }

  const firstPoint = pathPoints.split(' ')[0];
  const lastPoint = pathPoints.split(' ')[chartData.value.length - 1];
  const lastX = lastPoint.split(',')[0];
  const firstX = firstPoint.split(',')[0];

  return `M ${firstX},${height - padding} L ${pathPoints} L ${lastX},${height - padding} Z`;
});

// 添加获取当前是周几的计算函数
const getCurrentDayIndex = () => {
  const now = new Date();
  const currentDay = now.getDay(); // 0=周日, 1=周一, ..., 6=周六
  // 转换为0-6（周一到周日）的索引
  return currentDay === 0 ? 6 : currentDay - 1;
};

// 添加当前日期索引的响应式变量
const currentDayIndex = ref(getCurrentDayIndex());

// 获取当前活跃点（今日数据点）
const activePoint = computed(() => {
  const width = 120;
  const height = 50;
  const padding = 10;
  const maxValue = Math.max(...chartData.value.map(d => d.value));
  const safeMaxValue = maxValue > 0 ? maxValue : 1;

  // 使用当前日期索引而不是最后一个索引
  const currentIndex = currentDayIndex.value;
  const currentItem = chartData.value[currentIndex];

  const x = padding + (currentIndex * (width - 2 * padding)) / (chartData.value.length - 1);
  const y = height - padding - ((currentItem.value / safeMaxValue) * (height - 2 * padding));

  return { x, y, value: currentItem.value, label: currentItem.label };
});

const showRight = ref(false);
const showPopup = () => {
  showRight.value = true;
};

// 更换封面功能
const changeCover = () => {
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = 'image/*';

  input.onchange = (event: Event) => {
    const target = event.target as HTMLInputElement;
    const file = target.files?.[0];

    if (file) {
      if (!file.type.startsWith('image/')) {
        alert(messages[(currentLang.value as string) as keyof typeof messages].pleaseSelectImageFile);
        return;
      }

      if (file.size > 5 * 1024 * 1024) {
        alert(messages[currentLang.value as keyof typeof messages].imageSizeLimit);
        return;
      }

      isChangingCover.value = true;

      const reader = new FileReader();
      reader.onload = (e) => {
        backgroundImage.value = e.target?.result as string;
        isChangingCover.value = false;
      };
      reader.readAsDataURL(file);
    }
  };

  input.click();
};

// 退出登录
const logout = () => {
  try {
    if (confirm((messages[currentLang.value as keyof typeof messages].confirmLogout as string))) {
      userLogout();
      console.log('退出登录成功');
      router.push('/login');
    }
  } catch (error) {
    console.error('退出登录失败:', error);
  }
};

const navigateTo = (path: string) => {
  router.push(path);
};
const goface = () => {
  navigateTo('/faceo');
}

onMounted(() => {
  initUserData();
  loadFollowedUsers();
  loadCoupons();
  loadFavorites();
  // 初始化图表日期为当前语言
  updateChartDays();
  dataManager.loadFollows();
  dataManager.loadCoupons();
  dataManager.loadFavorites();
  loadPointsAndMembership();

  // 更新图表数据为真实运动数据
  updateChartData();

  // 添加延迟刷新，确保数据正确加载
  setTimeout(() => {
    console.log('延迟刷新运动数据...');
    updateChartData();
  }, 1000);

  // 监听页面可见性变化，当用户回到页面时刷新数据
  document.addEventListener('visibilitychange', handleVisibilityChange);
});

// 在组件卸载时清理事件监听
onUnmounted(() => {
  document.removeEventListener('visibilitychange', handleVisibilityChange);
});
</script>

<template>
  <div class="my-page">
    <!-- 顶部背景区域 -->
    <div class="header-bg">
      <img :src="backgroundImage" alt="背景图" class="bg-image" />
      <div class="more-btn" @click="changeCover" :class="{ 'changing': isChangingCover }">
        {{ isChangingCover ? messages[currentLang as keyof typeof messages].uploading : messages[currentLang as keyof
          typeof messages].changeCover }}
      </div>
      <i class="header-icon" @click="showPopup">⚙️</i>
      <van-popup v-model:show="showRight" position="right" :style="{ width: '70%', height: '100%' }">
        <!-- 设置菜单 -->
        <div class="settings-menu">
          <div class="settings-header">
            <span>{{ messages[currentLang as keyof typeof messages].settings }}</span> <i class="settings-icon">⚙️</i>
          </div>
          <div class="settings-divider"></div>

          <!-- 菜单项 -->
          <div class="settings-item">
            <span>{{ messages[currentLang as keyof typeof messages].personalInfo }}</span>
          </div>
          <div class="settings-item">
            <span>{{ messages[currentLang as keyof typeof messages].privacySecurity }}</span>
          </div>
          <div class="settings-item">
            <span>{{ messages[currentLang as keyof typeof messages].privacySettings }}</span>
          </div>
          <div class="settings-item">
            <span>{{ messages[currentLang as keyof typeof messages].notifications }}</span>
          </div>
          <div class="settings-item">
            <span>{{ messages[currentLang as keyof typeof messages].terms }}</span>
          </div>
          <div class="settings-item">
            <span>{{ messages[currentLang as keyof typeof messages].about }}</span>
          </div>

          <!-- 语言选择 -->
          <div class="settings-item language-selector" @click="showLangSelector = true">
            <span>{{ messages[currentLang as keyof typeof messages].language }}</span>
            <span class="current-lang">{{supportedLangs.find(l => l.code === currentLang)?.name}}</span>
          </div>

          <div class="settings-item" @click="navigateTo('/AIChat')">
            <span>{{ messages[currentLang as keyof typeof messages].customerService }}</span>
          </div>
          <div class="settings-item" @click="goface">
            <span>{{ messages[currentLang as keyof typeof messages].realNameAuth }}</span>
          </div>
          <div class="settings-divider"></div>
          <div class="logout-button" @click="logout">
            {{ messages[currentLang as keyof typeof messages].logout }}
          </div>
        </div>
      </van-popup>

      <!-- 语言选择弹窗 -->
      <van-popup v-model:show="showLangSelector" position="center" :style="{ width: '80%', maxWidth: '300px' }">
        <div class="lang-selector-container">
          <h3>{{ messages[currentLang as keyof typeof messages].language }}</h3>
          <div class="lang-list">
            <div v-for="lang in supportedLangs" :key="lang.code" class="lang-item" @click="changeLanguage(lang.code)">
              {{ lang.name }}
              <i v-if="currentLang === lang.code" class="lang-check">✓</i>
            </div>
          </div>
        </div>
      </van-popup>
    </div>

    <!-- 用户信息区域 -->
    <div class="user-info">
      <div class="avatar-container">
        <img :src="getUserAvatar()" alt="用户头像" class="avatar" />
      </div>
      <div class="user-details">
        <div class="user-id">
          用户ID：{{ userData.name }} <i class="edit-icon"></i>
        </div>
        <div class="user-level">
          {{ membershipCard?.currentLevel?.icon }} {{ membershipCard?.currentLevel?.name }}
        </div>
      </div>
    </div>

    <!-- 运动记录卡片 -->
    <div class="sport-card">
      <div class="sport-content">
        <div class="sport-info">
          <div class="sport-title">{{ messages[currentLang as keyof typeof messages].sportRecord }}</div>
          <div class="sport-data">
            <div>
              <span class="points-value">{{ userData.sportData.points }}</span>
              <span class="points-unit">{{ userData.sportData.unit }}</span>
            </div>
            <div class="points-desc">{{ userData.sportData.description }}</div>

            <!-- 新增积分显示 -->
            <div class="earned-points">
              <span class="points-label">已获得积分:</span>
              <span class="points-value">{{ Math.floor(userData.sportData.points / 10).toFixed(2) }}</span>
              <span class="points-unit">积分</span>
            </div>
            <div class="points-rule">
              <span>每10分钟1积分</span>
            </div>
          </div>
          <div class="chart-legend">
            <div class="legend-item">
              <div class="legend-dot"></div>
              <span>{{ messages[currentLang as keyof typeof messages].thisWeekData }}</span>
            </div>
          </div>
        </div>
        <div class="sport-chart">
          <!-- 优化后的SVG图表 -->
          <svg width="120" height="60" viewBox="0 0 120 60" class="chart-svg">
            <!-- 定义渐变 -->
            <defs>
              <linearGradient id="chartGradient" x1="0%" y1="0%" x2="0%" y2="100%">
                <stop offset="0%" style="stop-color:#4CAF50;stop-opacity:0.3" />
                <stop offset="100%" style="stop-color:#4CAF50;stop-opacity:0.05" />
              </linearGradient>
              <filter id="glow">
                <feGaussianBlur stdDeviation="2" result="coloredBlur" />
                <feMerge>
                  <feMergeNode in="coloredBlur" />
                  <feMergeNode in="SourceGraphic" />
                </feMerge>
              </filter>
            </defs>

            <!-- 网格线 -->
            <g class="grid-lines">
              <line x1="10" y1="15" x2="110" y2="15" stroke="#f0f0f0" stroke-width="0.5" />
              <line x1="10" y1="25" x2="110" y2="25" stroke="#f0f0f0" stroke-width="0.5" />
              <line x1="10" y1="35" x2="110" y2="35" stroke="#f0f0f0" stroke-width="0.5" />
            </g>

            <!-- 填充区域 -->
            <path :d="gradientPath" fill="url(#chartGradient)" class="chart-area" />

            <!-- 主线条 -->
            <polyline fill="none" stroke="#4CAF50" stroke-width="2.5" :points="chartPath" class="chart-line"
              filter="url(#glow)" />

            <!-- 数据点 -->
            <g class="data-points">
              <circle v-for="(item, index) in chartData" :key="index" :cx="10 + (index * 100) / (chartData.length - 1)"
                :cy="50 - 10 - ((item.value / Math.max(Math.max(...chartData.map(d => d.value)), 1)) * 30)" r="2"
                fill="#4CAF50" class="data-point" />
            </g>

            <!-- 活跃点（当前日期数据点） -->
            <circle :cx="activePoint.x" :cy="activePoint.y" r="4" fill="#4CAF50" class="active-point" />
            <circle :cx="activePoint.x" :cy="activePoint.y" r="6" fill="none" stroke="#4CAF50" stroke-width="2"
              opacity="0.5" class="active-point-ring" />
          </svg>

          <!-- 图表数值显示 -->
          <div class="chart-value">
            <span class="current-value">{{ activePoint.label }}</span>
            <span class="value-label">{{ messages[currentLang as keyof typeof messages].today }}</span>
          </div>
        </div>
      </div>

      <!-- 周数据概览 -->
      <div class="week-overview">
        <div class="week-title">{{ messages[currentLang as keyof typeof messages].weekOverview }}</div>
        <div class="week-data">
          <div v-for="(item, index) in chartData" :key="index" class="day-item"
            :class="{ 'active': index === currentDayIndex }">
            <div class="day-name">{{ item.day }}</div>
            <div class="day-bar">
              <div class="day-bar-fill"
                :style="{ height: (item.value / Math.max(Math.max(...chartData.map(d => d.value)), 1)) * 100 + '%' }">
              </div>
            </div>
            <div class="day-value">{{ item.value }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 功能菜单列表 -->
    <div class="menu-list">
      <div class="menu-item" @click="navigateTo('/mynotes')">
        <i class="menu-icon">📝</i>
        <span>{{ messages[currentLang as keyof typeof messages].myNotes }}</span>
      </div>
      <div class="menu-item" @click="showMyFavorites">
        <i class="menu-icon">⭐</i>
        <span>{{ messages[currentLang as keyof typeof messages].myFavorites }}</span>
        <span class="favorite-count">({{ favoriteStats.total }})</span>
      </div>
      <div class="menu-item" @click="showMyFollows">
        <i class="menu-icon">👥</i>
        <span>{{ messages[currentLang as keyof typeof messages].myFollows }}</span>
        <span class="follow-count">({{ followedUsers.length }})</span>
      </div>
      <div class="menu-item" @click="showMyCoupons">
        <i class="menu-icon">🎫</i>
        <span>{{ messages[currentLang as keyof typeof messages].myCoupons }}</span>
        <span class="coupon-count">({{ couponStats.total }})</span>
      </div>
      <div class="menu-item" @click="showMembershipCard = true">
        <i class="menu-icon">💳</i>
        <span>会员卡</span>
        <div class="member-level-badge" :style="{ backgroundColor: (membershipCard as any)?.currentLevel?.color }">
          {{ membershipCard?.currentLevel?.icon }} {{ membershipCard?.currentLevel?.name }}
        </div>
      </div>
      <div class="menu-item" @click="showPointsMall = true">
        <i class="menu-icon">🏪</i>
        <span>积分商城</span>
        <div class="points-badge">
          {{ userPoints }} 积分
        </div>
      </div>
      <div class="menu-item" @click="showPointsRecords = true">
        <i class="menu-icon">📊</i>
        <span>积分记录</span>
      </div>
      <div class="menu-item" @click="navigateTo('/shop')">
        <i class="menu-icon">🛒</i>
        <span>{{ messages[currentLang as keyof typeof messages].mall }}</span>
      </div>
    </div>

    <!-- 关注列表弹窗 -->
    <van-popup v-model:show="showFollowList" position="bottom" :style="{ height: '70%' }" round>
      <div class="follow-list-container">
        <div class="follow-list-header">
          <h3>{{ messages[currentLang as keyof typeof messages].followList }}</h3>
          <span class="follow-total">{{ messages[currentLang as keyof typeof messages].total }}{{ followedUsers.length
          }}{{ messages[currentLang as keyof typeof messages].total === '共' ? '人' : '' }}</span>
        </div>

        <div class="follow-list-content">
          <div v-if="followedUsers.length === 0" class="empty-follow">
            <p>{{ messages[currentLang as keyof typeof messages].noFollowedUsers }}</p>
            <p>{{ messages[currentLang as keyof typeof messages].discoverPeople }}</p>
          </div>

          <div v-for="user in followedUsers" :key="user.name" class="follow-user-item" @click="goToUserDetail(user)">
            <img :src="user.avatar" alt="头像" class="follow-avatar" />
            <div class="follow-user-info">
              <div class="follow-user-name">{{ user.name }}</div>
              <div class="follow-user-level">Lv.{{ user.level }} 运动达人</div>
              <div class="follow-time">{{ messages[currentLang as keyof typeof messages].followTime }}{{ user.followedAt
              }}</div>
            </div>
            <button class="unfollow-btn" @click.stop="unfollowUser(user.name)">
              {{ messages[currentLang as keyof typeof messages].cancelFollow }}
            </button>
          </div>
        </div>
      </div>
    </van-popup>

    <!-- 收藏列表弹窗 -->
    <van-popup v-model:show="showFavoriteList" position="bottom" :style="{ height: '80%' }" round>
      <div class="favorite-list-container">
        <div class="favorite-list-header">
          <h3>{{ messages[currentLang as keyof typeof messages].myFavoritesList }}</h3>
          <span class="favorite-total">{{ messages[currentLang as keyof typeof messages].total }}{{ favoriteStats.total
          }}{{ messages[currentLang as keyof typeof messages].total === '共' ? '个' : '' }}</span>
        </div>

        <!-- 收藏标签页 -->
        <div class="favorite-tabs">
          <div class="favorite-tab" :class="{ active: activeFavoriteTab === 'all' }" @click="activeFavoriteTab = 'all'">
            {{ messages[currentLang].total }}({{ favoriteStats.total }})
          </div>
          <div class="favorite-tab" :class="{ active: activeFavoriteTab === '跑步' }" @click="activeFavoriteTab = '跑步'">
            跑步({{ favoriteStats.byType.跑步 }})
          </div>
          <div class="favorite-tab" :class="{ active: activeFavoriteTab === '骑行' }" @click="activeFavoriteTab = '骑行'">
            骑行({{ favoriteStats.byType.骑行 }})
          </div>
          <div class="favorite-tab" :class="{ active: activeFavoriteTab === '瑜伽' }" @click="activeFavoriteTab = '瑜伽'">
            瑜伽({{ favoriteStats.byType.瑜伽 }})
          </div>
          <div class="favorite-tab" :class="{ active: activeFavoriteTab === '健身' }" @click="activeFavoriteTab = '健身'">
            健身({{ favoriteStats.byType.健身 }})
          </div>
        </div>

        <div class="favorite-list-content">
          <div v-if="filteredFavorites.length === 0" class="empty-favorite">
            <p>{{ messages[currentLang as keyof typeof messages].noFavorites }}</p>
            <p>{{ messages[currentLang as keyof typeof messages].collectVideos }}</p>
          </div>

          <div v-for="video in filteredFavorites" :key="video.id" class="favorite-item" @click="goToVideoDetail(video)">
            <img :src="video.img" alt="视频封面" class="favorite-image" />
            <div class="favorite-info">
              <div class="favorite-name">{{ video.name }}</div>
              <div class="favorite-type">{{ video.type }}</div>
              <div class="favorite-time">{{ messages[currentLang as keyof typeof messages].favoriteTime }}{{
                video.favoriteTime.slice(0, 16) }}</div>
            </div>
            <button class="remove-favorite-btn" @click.stop="removeFavorite(video.id)">
              {{ messages[currentLang as keyof typeof messages].removeFavorite }}
            </button>
          </div>
        </div>
      </div>
    </van-popup>

    <!-- 优惠券列表弹窗 -->
    <van-popup v-model:show="showCouponList" position="bottom" :style="{ height: '80%' }" round>
      <div class="coupon-list-container">
        <div class="coupon-list-header">
          <h3>{{ messages[currentLang as keyof typeof messages].myCouponsList }}</h3>
          <span class="coupon-total">{{ messages[currentLang as keyof typeof messages].total }}{{ couponStats.total }}{{
            messages[currentLang as keyof typeof messages].total === '共' ? '张' : '' }}</span>
        </div>

        <!-- 优惠券标签页 -->
        <div class="coupon-tabs">
          <div class="coupon-tab" :class="{ active: activeCouponTab === 'available' }"
            @click="activeCouponTab = 'available'">
            {{ messages[currentLang as keyof typeof messages].available }}({{ couponStats.available }})
          </div>
          <div class="coupon-tab" :class="{ active: activeCouponTab === 'used' }" @click="activeCouponTab = 'used'">
            {{ messages[currentLang as keyof typeof messages].used }}({{ couponStats.used }})
          </div>
          <div class="coupon-tab" :class="{ active: activeCouponTab === 'expired' }"
            @click="activeCouponTab = 'expired'">
            {{ messages[currentLang as keyof typeof messages].expired }}({{ couponStats.expired }})
          </div>
        </div>

        <div class="coupon-list-content">
          <div v-if="filteredCoupons.length === 0" class="empty-coupon">
            <p v-if="activeCouponTab === 'available'">{{ messages[currentLang as keyof typeof
              messages].noAvailableCoupons }}</p>
            <p v-else-if="activeCouponTab === 'used'">{{ messages[currentLang as keyof typeof messages].noUsedCoupons }}
            </p>
            <p v-else>{{ messages[currentLang as keyof typeof messages].noExpiredCoupons }}</p>
            <p>{{ messages[currentLang as keyof typeof messages].getMoreCoupons }}</p>
          </div>

          <div v-for="coupon in filteredCoupons" :key="coupon.id" class="coupon-item" :class="{
            'coupon-available': coupon.status === 'available' && new Date(coupon.expireDate) > new Date(),
            'coupon-used': coupon.status === 'used',
            'coupon-expired': coupon.status === 'expired' || new Date(coupon.expireDate) <= new Date()
          }">
            <div class="coupon-left">
              <div class="coupon-amount">
                <span class="coupon-symbol">¥</span>
                <span class="coupon-value">{{ coupon.amount.toFixed(0) }}</span>
              </div>
              <div class="coupon-condition">{{ messages[currentLang as keyof typeof messages].minSpend }}{{
                coupon.minAmount }}{{ messages[currentLang as keyof typeof messages].yuan }}</div>
            </div>

            <div class="coupon-right">
              <div class="coupon-name">{{ coupon.name }}</div>
              <div class="coupon-desc">{{ coupon.description }}</div>
              <div class="coupon-info">
                <span class="coupon-source">{{ messages[currentLang as keyof typeof messages].from }}{{ coupon.source
                }}</span>
                <span class="coupon-expire">{{ formatDate(coupon.expireDate) }}{{ messages[currentLang as keyof typeof
                  messages].expires }}</span>
              </div>
            </div>

            <div class="coupon-status">
              <span class="status-text">{{ getCouponStatusText(coupon) }}</span>
            </div>
          </div>
        </div>
      </div>
    </van-popup>

    <!-- 会员卡弹窗 -->
    <van-popup v-model:show="showMembershipCard" position="bottom" :style="{ height: '80%' }" round>
      <div class="membership-card-container">
        <div class="membership-card-header">
          <h3>我的会员卡</h3>
        </div>

        <div class="membership-card" v-if="membershipCard">
          <div class="card-background"
            :style="{ background: `linear-gradient(135deg, ${membershipCard.currentLevel.color}, ${membershipCard.currentLevel.color}88)` }">
            <div class="card-content">
              <div class="card-user-info">
                <img :src="membershipCard.user.avatar" alt="头像" class="card-avatar" />
                <div class="card-user-details">
                  <div class="card-username">{{ membershipCard.user.name }}</div>
                  <div class="card-member-since">会员时间：{{ membershipCard.memberSince }}</div>
                </div>
              </div>

              <div class="card-level-info">
                <div class="current-level">
                  <span class="level-icon">{{ membershipCard.currentLevel.icon }}</span>
                  <span class="level-name">{{ membershipCard.currentLevel.name }}</span>
                </div>
                <div class="points-info">
                  <span class="points-count">{{ membershipCard.points }}</span>
                  <span class="points-label">积分</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 升级进度 -->
          <div class="upgrade-progress" v-if="membershipCard.nextLevel">
            <div class="progress-header">
              <span>距离 {{ membershipCard.nextLevel.name }} 还需 {{ membershipCard.nextLevel.pointsRequired -
                membershipCard.points }} 积分</span>
            </div>
            <div class="progress-bar">
              <div class="progress-fill"
                :style="{ width: membershipCard.progress.percentage + '%', backgroundColor: membershipCard.nextLevel.color }">
              </div>
            </div>
          </div>

          <!-- 会员特权 -->
          <div class="member-benefits">
            <h4>当前特权</h4>
            <div class="benefits-list">
              <div v-for="benefit in membershipCard.currentLevel.benefits" :key="benefit" class="benefit-item">
                <i class="benefit-icon">✓</i>
                <span>{{ benefit }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </van-popup>

    <!-- 积分商城弹窗 -->
    <van-popup v-model:show="showPointsMall" position="bottom" :style="{ height: '80%' }" round>
      <div class="points-mall-container">
        <div class="points-mall-header">
          <h3>积分商城</h3>
          <div class="user-points">
            <span class="points-icon">💎</span>
            <span class="points-count">{{ userPoints }}</span>
            <span class="points-label">积分</span>
          </div>
        </div>

        <div class="points-products-grid">
          <div v-for="product in pointsProducts" :key="product.id" class="product-card"
            @click="exchangeProduct(product.id)">
            <div class="product-icon">{{ product.image }}</div>
            <div class="product-info">
              <div class="product-name">{{ product.name }}</div>
              <div class="product-description">{{ product.description }}</div>
              <div class="product-price">
                <span class="price-points">{{ product.pointsCost }}</span>
                <span class="price-label">积分</span>
              </div>
            </div>
            <div class="exchange-button" :class="{ disabled: userPoints < product.pointsCost }">
              {{ userPoints >= product.pointsCost ? '兑换' : '积分不足' }}
            </div>
          </div>
        </div>

        <div class="points-tips">
          <h4>💡 积分获取方式</h4>
          <p>• 每运动10分钟获得1积分</p>
          <p>• 会员等级越高，积分奖励倍率越高</p>
          <p>• 完成每日任务可获得额外积分</p>
        </div>
      </div>
    </van-popup>

    <!-- 积分记录弹窗 -->
    <van-popup v-model:show="showPointsRecords" position="bottom" :style="{ height: '70%' }" round>
      <div class="points-records-container">
        <div class="points-records-header">
          <h3>积分记录</h3>
          <div class="points-summary">
            <div class="summary-item">
              <span class="summary-label">当前积分</span>
              <span class="summary-value">{{ pointsStats.current }}</span>
            </div>
            <div class="summary-item">
              <span class="summary-label">累计获得</span>
              <span class="summary-value earned">+{{ pointsStats.totalEarned }}</span>
            </div>
            <div class="summary-item">
              <span class="summary-label">累计消费</span>
              <span class="summary-value spent">-{{ pointsStats.totalSpent }}</span>
            </div>
          </div>
        </div>

        <div class="points-records-list">
          <div v-if="pointsRecords.length === 0" class="empty-records">
            <p>暂无积分记录</p>
            <p>快去运动获取积分吧！</p>
          </div>

          <div v-for="record in pointsRecords" :key="record.id" class="record-item">
            <div class="record-info">
              <div class="record-description">{{ record.description }}</div>
              <div class="record-source">{{ record.source }}</div>
              <div class="record-time">{{ new Date(record.createTime).toLocaleString() }}</div>
            </div>
            <div class="record-amount" :class="record.type">
              {{ record.type === 'earn' ? '+' : '-' }}{{ record.amount }}
            </div>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<style scoped>
/* 语言选择相关样式 */
.language-selector {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.current-lang {
  color: #4CAF50;
  font-weight: 500;
}

.lang-selector-container {
  padding: 20px;
}

.lang-selector-container h3 {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}

.lang-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.lang-item {
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s;
}

.lang-item:hover {
  background-color: #e8f5e9;
}

.lang-check {
  color: #4CAF50;
  font-weight: bold;
}

/* 运动记录卡片优化 */
.sport-card {
  background-color: white;
  border-radius: 15px;
  padding: 20px;
  margin: 15px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.sport-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.sport-info {
  display: flex;
  flex-direction: column;
  width: 45%;
}

.sport-title {
  font-size: 16px;
  color: #333;
  font-weight: 600;
  margin-bottom: 8px;
}

.sport-data {
  display: flex;
  flex-direction: column;
  margin-bottom: 15px;
}

.points-value {
  font-size: 32px;
  font-weight: bold;
  color: #4CAF50;
  line-height: 1;
}

.points-unit {
  font-size: 14px;
  color: #666;
  margin-left: 5px;
}

.points-desc {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

/* 图表图例 */
.chart-legend {
  display: flex;
  align-items: center;
}

.legend-item {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #666;
}

.legend-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #4CAF50;
  margin-right: 6px;
}

/* 图表容器 */
.sport-chart {
  width: 50%;
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
}

/* SVG图表样式 */
.chart-svg {
  width: 100%;
  height: auto;
  overflow: visible;
}

.grid-lines {
  opacity: 0.3;
}

.chart-area {
  transition: all 0.3s ease;
}

.chart-line {
  stroke-linecap: round;
  stroke-linejoin: round;
  transition: all 0.3s ease;
}

.data-point {
  transition: all 0.3s ease;
}

.data-point:hover {
  r: 3;
  fill: #2E7D32;
}

.active-point {
  animation: pulse 2s infinite;
}

.active-point-ring {
  animation: ripple 2s infinite;
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }

  50% {
    transform: scale(1.1);
  }

  100% {
    transform: scale(1);
  }
}

@keyframes ripple {
  0% {
    opacity: 0.5;
    transform: scale(1);
  }

  100% {
    opacity: 0;
    transform: scale(1.5);
  }
}

/* 图表数值显示 */
.chart-value {
  margin-top: 10px;
  text-align: center;
}

.current-value {
  display: block;
  font-size: 18px;
  font-weight: bold;
  color: #4CAF50;
}

.value-label {
  font-size: 12px;
  color: #666;
}

/* 积分信息样式 */
.points-info {
  margin-top: 8px;
  font-size: 14px;
}

.earned-points {
  color: #4CAF50;
  font-weight: bold;
  margin-right: 8px;
}

.points-rule {
  color: #666;
  font-size: 12px;
}

/* 周数据概览 */
.week-overview {
  border-top: 1px solid #f0f0f0;
  padding-top: 20px;
}

.week-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 15px;
  font-weight: 500;
}

.week-data {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
}

.day-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
  margin: 0 2px;
}

.day-name {
  font-size: 10px;
  color: #999;
  margin-bottom: 8px;
}

.day-bar {
  width: 12px;
  height: 30px;
  background-color: #f5f5f5;
  border-radius: 6px;
  position: relative;
  overflow: hidden;
}

.day-bar-fill {
  position: absolute;
  bottom: 0;
  width: 100%;
  background: linear-gradient(to top, #4CAF50, #66BB6A);
  border-radius: 6px;
  transition: height 0.3s ease;
}

.day-item.active .day-bar-fill {
  background: linear-gradient(to top, #2E7D32, #4CAF50);
  box-shadow: 0 0 8px rgba(76, 175, 80, 0.4);
}

.day-value {
  font-size: 10px;
  color: #666;
  margin-top: 6px;
  font-weight: 500;
}

.day-item.active .day-value {
  color: #4CAF50;
  font-weight: bold;
}

.day-item.active .day-name {
  color: #4CAF50;
  font-weight: bold;
}

/* 其他原有样式保持不变 */
.my-page {
  padding: 0;
  padding-bottom: 20px;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header-bg {
  position: relative;
  height: 150px;
  overflow: hidden;
}

.bg-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: all 0.3s ease;
}

.more-btn {
  position: absolute;
  right: 15px;
  bottom: 15px;
  background-color: rgba(255, 255, 255, 0.7);
  padding: 5px 10px;
  border-radius: 15px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  user-select: none;
}

.more-btn:hover {
  background-color: rgba(255, 255, 255, 0.9);
  transform: translateY(-1px);
}

.more-btn.changing {
  background-color: rgba(33, 150, 243, 0.8);
  color: white;
  pointer-events: none;
}

.user-info {
  display: flex;
  padding: 15px;
  background-color: white;
  border-radius: 10px 10px 0 0;
  margin-top: -20px;
  position: relative;
  z-index: 1;
}

.avatar-container {
  margin-right: 15px;
  margin-top: -30px;
}

.avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  border: 3px solid white;
  background-color: #f0f0f0;
}

.user-id {
  font-weight: bold;
  display: flex;
  align-items: flex-start;
}

.edit-icon {
  margin-left: 10px;
  color: #999;
  font-size: 14px;
}

.user-level {
  color: #666;
  font-size: 14px;
  margin-top: 5px;
}

.menu-list {
  background-color: white;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
  margin-bottom: 30px;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 12px 15px;
  border-bottom: 1px solid #f0f0f0;
}

.menu-item:last-child {
  border-bottom: none;
}

.menu-icon {
  margin-right: 15px;
  font-size: 16px;
}

.header-icon {
  position: absolute;
  top: 15px;
  right: 15px;
  font-size: 24px;
  color: white;
}

.settings-menu {
  padding: 15px;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #fff;
}

.settings-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  font-weight: bold;
}

.settings-divider {
  height: 1px;
  background-color: #eee;
  margin: 10px 0;
  width: 100%;
}

.settings-item {
  padding: 12px 0;
  border-bottom: 1px solid #f5f5f5;
  color: #333;
}

.logout-button {
  margin-top: auto;
  padding: 12px 0;
  text-align: center;
  color: #2196F3;
  font-weight: bold;
  cursor: pointer;
}

/* 关注数量显示 */
.follow-count {
  color: #4CAF50;
  font-size: 12px;
  margin-left: 5px;
}

/* 收藏数量显示 */
.favorite-count {
  color: #ff6b35;
  font-size: 12px;
  margin-left: 5px;
}

/* 关注列表弹窗样式 */
.follow-list-container {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #fff;
}

.follow-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  font-weight: bold;
}

.follow-list-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.follow-total {
  font-size: 14px;
  color: #666;
}

.follow-user-item {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.2s;
}

.follow-user-item:hover {
  background-color: #f9f9f9;
}

.follow-user-item:last-child {
  border-bottom: none;
}

.follow-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 12px;
}

.follow-user-info {
  flex: 1;
}

.follow-user-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.follow-user-level {
  font-size: 14px;
  color: #666;
  margin-bottom: 2px;
}

.follow-time {
  font-size: 12px;
  color: #999;
}

.unfollow-btn {
  padding: 6px 12px;
  background-color: #f5f5f5;
  border: 1px solid #ddd;
  border-radius: 4px;
  color: #666;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s;
}

.unfollow-btn:hover {
  background-color: #ff4757;
  color: white;
  border-color: #ff4757;
}

.empty-follow {
  text-align: center;
  padding: 60px 20px;
  color: #999;
}

.empty-follow p {
  margin: 10px 0;
  font-size: 14px;
}

/* 收藏列表弹窗样式 */
.favorite-list-container {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f7f8fa;
}

.favorite-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  font-weight: bold;
  background-color: #fff;
  margin: -20px -20px 0 -20px;
  padding: 20px;
}

.favorite-list-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.favorite-total {
  font-size: 14px;
  color: #666;
}

/* 收藏标签页 */
.favorite-tabs {
  display: flex;
  background-color: #fff;
  margin: 10px -20px 0 -20px;
  padding: 0 20px;
  overflow-x: auto;
}

.favorite-tab {
  flex-shrink: 0;
  text-align: center;
  padding: 15px 12px;
  font-size: 14px;
  color: #666;
  border-bottom: 2px solid transparent;
  cursor: pointer;
  transition: all 0.3s;
  white-space: nowrap;
}

.favorite-tab.active {
  color: #ff6b35;
  border-bottom-color: #ff6b35;
  font-weight: 500;
}

.favorite-list-content {
  flex: 1;
  overflow-y: auto;
  margin-top: 10px;
}

/* 收藏项目 */
.favorite-item {
  display: flex;
  align-items: center;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 12px;
  padding: 12px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.favorite-item:hover {
  background-color: #f5f5f5;
}

.favorite-image {
  width: 80px;
  height: 60px;
  border-radius: 6px;
  object-fit: cover;
  margin-right: 12px;
}

.favorite-info {
  flex: 1;
}

.favorite-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.favorite-type {
  font-size: 12px;
  color: #ff6b35;
  background-color: #fff2f0;
  padding: 2px 8px;
  border-radius: 12px;
  display: inline-block;
  margin-bottom: 4px;
}

.favorite-time {
  font-size: 12px;
  color: #999;
}

.remove-favorite-btn {
  background-color: #ff4757;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.remove-favorite-btn:hover {
  background-color: #ff3742;
}

.empty-favorite {
  text-align: center;
  padding: 60px 20px;
  color: #999;
}

.empty-favorite p {
  margin: 8px 0;
}

/* 优惠券相关样式 */
.coupon-count {
  color: #ff6b35;
  font-size: 12px;
  margin-left: 5px;
}

.coupon-list-container {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f7f8fa;
}

.coupon-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  font-weight: bold;
  background-color: #fff;
  margin: -20px -20px 0 -20px;
  padding: 20px;
}

.coupon-list-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.coupon-total {
  font-size: 14px;
  color: #666;
}

/* 优惠券标签页 */
.coupon-tabs {
  display: flex;
  background-color: #fff;
  margin: 10px -20px 0 -20px;
  padding: 0 20px;
}

.coupon-tab {
  flex: 1;
  text-align: center;
  padding: 15px 0;
  font-size: 14px;
  color: #666;
  border-bottom: 2px solid transparent;
  cursor: pointer;
  transition: all 0.3s;
}

.coupon-tab.active {
  color: #4CAF50;
  border-bottom-color: #4CAF50;
  font-weight: 500;
}

.coupon-list-content {
  flex: 1;
  overflow-y: auto;
  margin-top: 10px;
}

/* 优惠券项目 */
.coupon-item {
  display: flex;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 12px;
  overflow: hidden;
  position: relative;
}

.coupon-available {
  border-left: 4px solid #4CAF50;
}

.coupon-used {
  border-left: 4px solid #999;
  opacity: 0.6;
}

.coupon-expired {
  border-left: 4px solid #f5222d;
  opacity: 0.6;
}

.coupon-left {
  width: 80px;
  background: linear-gradient(135deg, #4CAF50, #45a049);
  color: white;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 15px 10px;
  position: relative;
}

.coupon-used .coupon-left {
  background: linear-gradient(135deg, #999, #888);
}

.coupon-expired .coupon-left {
  background: linear-gradient(135deg, #f5222d, #d4001a);
}

.coupon-amount {
  display: flex;
  align-items: baseline;
}

.coupon-symbol {
  font-size: 12px;
  margin-right: 2px;
}

.coupon-value {
  font-size: 24px;
  font-weight: bold;
  line-height: 1;
}

.coupon-condition {
  font-size: 10px;
  margin-top: 4px;
  opacity: 0.9;
}

.coupon-right {
  flex: 1;
  padding: 15px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.coupon-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.coupon-desc {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.coupon-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.coupon-source {
  font-size: 12px;
  color: #999;
}

.coupon-expire {
  font-size: 12px;
  color: #f5222d;
}

.coupon-status {
  position: absolute;
  top: 10px;
  right: 10px;
}

.status-text {
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
  background-color: #f0f0f0;
  color: #666;
}

.empty-coupon {
  text-align: center;
  padding: 60px 20px;
  color: #999;
}

.empty-coupon p {
  margin: 10px 0;
  font-size: 14px;
}

/* 会员等级徽章 */
.member-level-badge {
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  color: white;
  margin-left: auto;
}

/* 积分徽章 */
.points-badge {
  padding: 2px 8px;
  border-radius: 12px;
  background: linear-gradient(45deg, #ff6b6b, #feca57);
  color: white;
  font-size: 12px;
  margin-left: auto;
}

/* 会员卡样式 */
.membership-card-container {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
}

.membership-card {
  margin-top: 20px;
}

.card-background {
  border-radius: 16px;
  padding: 20px;
  color: white;
  margin-bottom: 20px;
}

.card-user-info {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.card-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-right: 15px;
}

.card-username {
  font-size: 18px;
  font-weight: bold;
}

.card-member-since {
  font-size: 12px;
  opacity: 0.8;
}

.card-level-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.current-level {
  display: flex;
  align-items: center;
}

.level-icon {
  font-size: 24px;
  margin-right: 8px;
}

.level-name {
  font-size: 16px;
  font-weight: bold;
}

.points-info {
  text-align: right;
}

.points-count {
  font-size: 24px;
  font-weight: bold;
}

.points-label {
  font-size: 12px;
  opacity: 0.8;
}

/* 升级进度 */
.upgrade-progress {
  margin-bottom: 20px;
}

.progress-header {
  font-size: 14px;
  margin-bottom: 8px;
  color: #666;
}

.progress-bar {
  height: 8px;
  background: #f0f0f0;
  border-radius: 4px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  transition: width 0.3s ease;
}

/* 会员特权 */
.member-benefits h4 {
  margin-bottom: 15px;
  color: #333;
}

.benefits-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.benefit-item {
  display: flex;
  align-items: center;
  padding: 8px;
  background: #f8f9fa;
  border-radius: 8px;
}

.benefit-icon {
  color: #27ae60;
  margin-right: 10px;
  font-weight: bold;
}

/* 积分商城样式 */
.points-mall-container {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
}

.points-mall-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.user-points {
  display: flex;
  align-items: center;
  background: linear-gradient(45deg, #667eea, #764ba2);
  color: white;
  padding: 8px 16px;
  border-radius: 20px;
}

.points-icon {
  margin-right: 5px;
}

.points-products-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 15px;
  margin-bottom: 30px;
}

.product-card {
  display: flex;
  align-items: center;
  padding: 15px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: transform 0.2s;
}

.product-card:hover {
  transform: translateY(-2px);
}

.product-icon {
  font-size: 32px;
  margin-right: 15px;
}

.product-info {
  flex: 1;
}

.product-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 4px;
}

.product-description {
  font-size: 12px;
  color: #666;
  margin-bottom: 8px;
}

.product-price {
  display: flex;
  align-items: center;
}

.price-points {
  font-size: 18px;
  font-weight: bold;
  color: #e74c3c;
  margin-right: 4px;
}

.price-label {
  font-size: 12px;
  color: #666;
}

.exchange-button {
  padding: 8px 16px;
  background: #27ae60;
  color: white;
  border-radius: 20px;
  font-size: 14px;
  font-weight: bold;
}

.exchange-button.disabled {
  background: #bdc3c7;
  cursor: not-allowed;
}

.points-tips {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 12px;
}

.points-tips h4 {
  margin-bottom: 10px;
  color: #333;
}

.points-tips p {
  margin: 5px 0;
  color: #666;
  font-size: 14px;
}

/* 积分记录样式 */
.points-records-container {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
}

.points-summary {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
  margin-top: 15px;
  margin-bottom: 20px;
}

.summary-item {
  text-align: center;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 8px;
}

.summary-label {
  display: block;
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.summary-value {
  font-size: 16px;
  font-weight: bold;
}

.summary-value.earned {
  color: #27ae60;
}

.summary-value.spent {
  color: #e74c3c;
}

.points-records-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.record-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.record-description {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 4px;
}

.record-source {
  font-size: 12px;
  color: #666;
  margin-bottom: 2px;
}

.record-time {
  font-size: 11px;
  color: #999;
}

.record-amount {
  font-size: 16px;
  font-weight: bold;
}

.record-amount.earn {
  color: #27ae60;
}

.record-amount.spend {
  color: #e74c3c;
}

.empty-records {
  text-align: center;
  padding: 40px 20px;
  color: #666;
}
</style>